package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"recruit-pro/cache"
	"recruit-pro/models"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size

	var work []models.Work
	redis_key := "list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Find(&work)
		jsonData, _ := json.Marshal(work)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &work)
	}
	var count int64
	models.DB.Model(&models.Work{}).Count(&count)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  work,
		"count": count,
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var work models.Work
	models.DB.Where("id = ?", id).First(&work)
	redis_key := "work_id" + id
	cache.Rdb.Get(cache.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": work,
	})
	return
}
func CollectionList(c *gin.Context) {
	var collection []models.Collection
	redis_key := "collection_list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Find(&collection)
		jsonData, _ := json.Marshal(collection)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &collection)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": collection,
	})
	return
}
